const Koa = require('koa')
const koaBody = require('koa-body')
const koaStatic = require('koa-static')
const mongoose = require('mongoose')
const config = require('./config')
const errorMiddleware = require('./middlewares/error.middleware')
const logMiddleware = require('./middlewares/log.middleware')
const path = require('path')
const fs = require('fs')
const logger = require('./utils/logger')

const app = new Koa()
app.use(koaBody({
  multipart: true,
  formidable: {
    keepExtensions: true,
    uploadDir: path.resolve(__dirname, '../uploads'),
    maxFileSize: 200 * 1024 * 1024    // 设置上传文件大小最大限制，默认2M
  }
}))
app.use(koaStatic(path.join(__dirname, '../uploads')))
app.use(koaStatic(path.join(__dirname, '../public')))
app.use(async (ctx, next) => {
  await next();
  if (parseInt(ctx.status) === 404) {
    ctx.type = 'html';
    ctx.body = fs.createReadStream(path.join(__dirname, '../public/index.html'));
  } else if (parseInt(ctx.status) === 401) {
    ctx.body = {
      message: 'Token验证失败，请重新登录'
    }
  } else if (parseInt(ctx.status) === 500) {
    logger.error('internal error ', ctx.body)
    ctx.body = {
      message: '服务器内部错误'
    }
  }
})

app.use(errorMiddleware)
app.use(logMiddleware)
app.on('error', (err, ctx) => {
  console.error('server error', err)
});

app.use(async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*");
  ctx.set("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS, PATCH");
  // 请求头设置
  ctx.set(
    "Access-Control-Allow-Headers",
    `Content-Type, Content-Length, Authorization, Accept, X-Requested-With, x-token,sessionToken,token`
  );
  if (ctx.method == "OPTIONS") {
    ctx.body = 200;
  } else {
    await next();
  }
})
mongoose.connect(config.mongoUrl, config.mongoOptions).then(() => {
  console.log('db connect success')
}).catch(err => {
  console.log('db connect failed', err.message)
})

module.exports = (routes) => {
  routes.forEach(router => {
    app.use(router.routes())
  })
  app.listen(3000, () => {
    console.log('服务已经启动, http://localhost:3000')
  })
}
